﻿using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using CommonTools;
using shop.Model;
using System.Threading.Tasks;
using System.Dynamic;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Xml.Linq;

namespace shop.Bll
{

	/// <summary>  </summary>
  	public class LogisticsFeeConfigBll : MyDocBaseBll<LogisticsFeeConfig>, IPageBll<LogisticsFeeConfigItem>
  	{

		/// <summary> 单据类型, 每个单据唯一 </summary>
		public override string DocFlag => DocFlagEnum.LogisticsFeeConfig;


        public override string SavePermission => "02.04.2";

        public override string ModifyPermission => "02.04.3";

        public override string DeletePermission => "02.04.4";

        public override string CheckPermission => "02.04.5";

        public override string PrintPermission => "";


        public Action<int> TurnPage { set; get; }

        public override bool CheckDocument(LogisticsFeeConfig doc, IUser user, out string err)
        {
            
            if (doc == null)
            {
                err = Model.CN.Msg_Dociswrong;
                return false;
            }
            if (doc.DocId ==0)
            {
                err = Model.CN.Msg_QueryBeforeModify;
                return false;
            }

            doc.IsChecked = 1;

            DB.FSql.Update<LogisticsFeeConfig>()
                .SetSource(doc)
                .Set(a => a.IsChecked, doc.IsChecked)
                .ExecuteAffrows();

            err = "";
            return true;

        }


		public override bool UnCheckDocument(LogisticsFeeConfig doc, IUser user, out string err)
        {
            if (doc == null)
            {
                err = Model.CN.Msg_Dociswrong;
                return false;
            }
            if (doc.DocId == 0)
            {
                err = Model.CN.Msg_QueryBeforeModify;
                return false;
            }

            doc.IsChecked = 0;

            DB.FSql.Update<LogisticsFeeConfig>()
                .SetSource(doc)
                .Set(a => a.IsChecked, doc.IsChecked)
                .ExecuteAffrows();

            err = "";
            return true;

        }



        #region 查询方法: 按照 id,编号, 日期...


        public override IEnumerable<LogisticsFeeConfig> Query(DateTime? begin, DateTime? end, string keyWord, QueryDateEnum dateEnum = QueryDateEnum.OccurDate, params string[] args)
        {
            return base.Query(null, null, keyWord, dateEnum, args);
        }

        #endregion

        /// <summary> 创建单据 </summary>
        public override LogisticsFeeConfig CreateDoc()
        {
            return new LogisticsFeeConfig() { DocFlag = this.DocFlag };
        }





		/// <summary> 删除单据 </summary>
		public override bool Delete(LogisticsFeeConfig doc, IUser user, out string err)
        {
            doc.Isdel = true;
            doc.IsdelDate = DateTime.Now;

            if( base.Delete(doc, user, out err))
            {
                DB.FSql.Update<LogisticsFeeConfigItem>()
                    .Where(a => a.Isdel == false && a.DocId == doc.DocId)
                    .Set(a => a.Isdel, true)
                    .ExecuteAffrows();
                return true;
            }
            else
            {
                return false;
            }
        }


		/// <summary> 保存,修改 </summary>
        public override bool Save(LogisticsFeeConfig doc, IUser user, out string err)
        {
            err = "";
            if (doc == null)
            {
				err = Model.CN.Msg_SystemError;  // "系统错误, 请联系管理员!";
                return false;
            }

            doc.PreparedDate = doc.OccurDate.ToDate();

            //if (string.IsNullOrEmpty(doc.Customer) || string.IsNullOrEmpty(doc.CustomerId))
            //{
            //    err += "客户名称不能为空!";
            //}

            //else if (string.IsNullOrEmpty(doc.Company))
            //{
            //    err += "开票单位不能为空!";
            //}


            // 其他检查
            int i = 1;
            foreach (var item in doc.Items)
            {
                item.ItemId = i; //排序 
                string str = "";
                if (string.IsNullOrEmpty(item.Method) )
                {
                    str +=  "核算方式不能为空!";
                }
                //else if ( item.OccurDate == null)
                //{
                //    str += "开票日期不能为空!";
                //}

                //追加到err;
                if (str != "")
                    err += string.Format(Model.CN.Msg_itemError, i, str); // $"第{i}行: {str} \r\n;";


                i++;
            }


            if (err !="")
            {
                return false;   
            }

            //默认值
            doc.Isdel = false;
            if (doc.DocId ==0)
            {
                doc.IsChecked = 0;

            }

            return base.Save(doc, user, out err);

        }

        public override void SaveItems(LogisticsFeeConfig doc, DateTime time)
        {
            //删除旧的
            DB.FSql.Update<LogisticsFeeConfigItem>()
                .Where(a => a.Isdel == false && a.DocId == doc.DocId)
                .Set(a => a.Isdel, true)
                .ExecuteAffrows();

            foreach (var item in doc.Items)
            {
                item.DocId = doc.DocId;
                item.Isdel = false;
                //item.OccurDate = doc.OccurDate;
            }


            DB.FSql.InsertOrUpdate<LogisticsFeeConfigItem>()
                .SetSource(doc.Items)
                //.IgnoreColumns(nameof(LogisticsFeeConfig.ch))
                .ExecuteAffrows();

        }

        public List<LogisticsFeeConfigItem> GetItems(LogisticsFeeConfig doc)
        {
            return DB.FSql.Select<LogisticsFeeConfigItem>()
                .Where(a => a.Isdel == false && a.DocId == doc.DocId)
                .ToList()
                .OrderBy(a => a.ItemId)
                .ToList();
        }



        public async Task<List<LogisticsFeeConfigItem>> QueryAll()
        {
            return await DB.FSql.Select<LogisticsFeeConfigItem>()
                .Where(a => a.Isdel == false)
                .OrderBy(a => a.DocId)
                .OrderBy(a => a.ItemId)
                .ToListAsync();
        }



        /// <summary> 费用报表明细 </summary>
        public async Task<IEnumerable<LogiFeeReport>> QueryFeeReportDetails(DateTime begin, DateTime end, bool onlyOutStock)
        {
            // 物流单号	货品数量	订单编号	原始单号	订单类型	仓库	店铺	商家编码	收货地区	物流公司	快递老板	客服备注	发货时间	结算运费	结算重量

            begin = begin.Date;
            end = end.LastTimeOfDay();


            //需要物流账单, 出库信息, 均摊设置, 快递公司简称
            //参数要日期范围, 


            //出库信息, 账单
            //var res = await DB.FSql
            //    .Select<OutStockItem, LogisticsBillItem>()
            //    .LeftJoin((a, b) => a.logistics_no == b.LogisticCode && b.BillFlag == "快递账单" && b.FMonth >= begin && b.FMonth <= end)
            //    .Where((a, b) => a.consign_time >= begin && a.consign_time <= end)
            //    .GroupBy((a,b)=> new {a.consign_time,  a.logistics_no, a.logistics_name, a.receiver_address, a.receiver_position, a.rece_province, a.rece_city, a.rece_county, a.cs_remark , a.trade_no,a.src_tids,a.trade_type,a.warehouse, a.shop_name,})
            //    .ToListAsync(a => new LogiFeeReport()
            //    {
            //        consign_time = a.Key.consign_time,
            //        logistics_no = a.Key.logistics_no,
            //        logistics_name = a.Key.logistics_name,
            //        weight = a.Sum(a.Value.Item2.BillWeight),
            //        post_amount = a.Sum(a.Value.Item2.TotalFee),
            //        receiver_address = a.Key.receiver_address,
            //        receiver_position = a.Key.receiver_position,
            //        rece_province = a.Key.rece_province,
            //        rece_city = a.Key.rece_city,
            //        rece_county = a.Key.rece_county,
            //        cs_remark = a.Key.cs_remark,
            //        NotInOutstock = false,
            //        num = a.Sum(a.Value.Item1.num),    // 货品数量是从 LogisticsBillItem 里查询的吗, 
            //        trade_no = a.Key.trade_no,
            //        src_tids = a.Key.src_tids,
            //        trade_type = a.Key.trade_type,
            //        warehouse = a.Key.warehouse,
            //        shop_name = a.Key.shop_name,
            //    });


            var cmd = @"SELECT a.consign_time, a.logistics_no, a.logistics_name, a.receiver_address, a.receiver_position, a.rece_province,
       a.rece_city, a.rece_county, a.cs_remark, a.trade_no, a.src_tids, a.trade_type, a.warehouse, a.shop_name, a.num ,
	   b.BillWeight AS weight, b.TotalFee AS post_amount,spec_no
FROM (
	SELECT a.consign_time,  a.logistics_no, a.logistics_name, a.receiver_address, a.receiver_position, a.rece_province, a.rece_city, a.rece_county, a.cs_remark , a.trade_no,a.src_tids,a.trade_type,a.warehouse, a.shop_name ,
		SUM(a.num) AS num  , a.spec_no
	FROM dbo.OutStockItem AS a WITH(NOLOCK)
	where consign_time BETWEEN @begin AND @end 
	GROUP BY a.consign_time,  a.logistics_no, a.logistics_name, a.receiver_address, a.receiver_position, a.rece_province, a.rece_city, a.rece_county, a.cs_remark , a.trade_no,a.src_tids,a.trade_type,a.warehouse, a.shop_name , a.spec_no
) AS a
LEFT JOIN (SELECT LogisticCode, SUM(BillWeight) BillWeight, SUM(TotalFee) TotalFee FROM dbo.LogisticsBillItem WITH(NOLOCK) 
	WHERE BillFlag ='快递账单' AND FMonth BETWEEN @begin AND @end 
	GROUP BY LogisticCode
) AS b ON a.logistics_no= b.LogisticCode ";

            //var pr = new[] {
            //    new SqlParameter("@begin", begin),
            //    new SqlParameter("@end", end),
            //};

            //var res = await DB.FSql.Ado.ExecuteDataTableAsync(CommandType.Text, cmd, pr);
            //var res = await DB.FSql.Select<object>()
            //    .WithSql(cmd, pr)
            //    .ToListAsync<LogiFeeReport>();
            var res = await DB.FSql.Ado.QueryAsync<LogiFeeReport>(cmd, new { begin, end});
                


            //if(!onlyOutStock)
            //{
                //只有账单 没出库的 
                var notInOutList = await DB.FSql
                   .Select<LogisticsBillItem, OutStockItem>()
                   .LeftJoin((a, b) => b.logistics_no == a.LogisticCode && b.consign_time >= begin && b.consign_time <= end)
                   .Where((a, b) => a.FMonth >= begin && a.FMonth <= end && a.BillFlag == "快递账单")
                   .Where((a, b) => b == null)
                   .ToListAsync((a, b) => new LogiFeeReport()
                   {
                       consign_time = a.DeliveryTime,
                       logistics_no = a.LogisticCode,
                       //logistics_name = a.LogisticsCompany,
                       LogiAcct = a.LogiAcct,
                       weight = a.BillWeight,
                       post_amount = a.TotalFee,
                       rece_province = a.ReceiveProvince,
                       rece_city = a.ReceiveCity,
                       shop_name = a.ShopName,
                       NotInOutstock = true,    //无出库信息的
                       spec_no= b.spec_no,
                   });

                res.AddRange(notInOutList);
            //}
           



            //快递账户
            var logiInfos = await DB.FSql.Select<LogiInfo>()
                .Where(a => a.isdel == false && string.IsNullOrEmpty(a.LogiAcct) == false)
                .ToListAsync();

            // 移除代发的
            var daifa = logiInfos.Where(a => a.IsAgent == true).Select(a => a.logistics_name).ToArray();

            res = res
                .Where(a => daifa.Contains(a.logistics_name) == false)
                .ToList();

            //按照快递模板查找快递账户
            foreach (var item in res)
            {
                var findAcct = logiInfos.FirstOrDefault(a => a.logistics_name == item.logistics_name)?.LogiAcct;
                if (string.IsNullOrEmpty(findAcct) == false)
                {
                    item.LogiAcct = findAcct;
                }
            }


            // 猪猪快递云的信息
            var logiTrace = await DB.FSql.Select<LogiTrace>()
                .Where(a => a.DeliveryTime >= begin && a.DeliveryTime <= end && a.isdel == false)   // 需要区分时间吗 
                .ToListAsync(a => new
                {
                    a.logistics_no,
                    a.DeliveryTime,
                    a.LogisticsStatus,
                    a.ItemsCount,
                });


            //生成报表基础数据
            foreach (var a in res)
            {
                decimal forecast = 0m;

                if (a.post_amount <= 0)
                {
                    //快递条数少于等于2条 的属于未发货, 不进行预估,
                    a.NoLogiTrace = !(logiTrace.Any(c => c.logistics_no == c.logistics_no && c.ItemsCount > 2));    //有没有快递记录
                    if (a.NoLogiTrace == false)
                    {
                        forecast = Yugu(a, res);
                    }
                }
                else
                {
                    a.NoLogiTrace = false;
                }

                a.IsForecast = forecast > 0;
                a.ForecastAmount = forecast;
            }


            return res
                .OrderBy(a => a.LogiAcct)
                .ToList();
        }



        /// <summary> 查询快递费用报表 </summary>
        public async Task<DataTable> QueryFeeReport(DateTime begin, DateTime end)
        {
            begin = begin.Date;
            end = end.LastTimeOfDay();

            var res = (await QueryFeeReportDetails(begin, end, false)) as List<LogiFeeReport>;


            //费用账单, 
            // todo 怎么用 
            var feeBill = await DB.FSql.Select<LogisticsBillItem>()
                .Where(a => a.FMonth >= begin && a.FMonth <= end && a.BillFlag == "物流费用")
                .ToListAsync();

            var billTotal = await DB.FSql.Select<LogisticsBillItem>()
            .Where(a => a.FMonth >= begin && a.FMonth <= end && a.BillFlag == "快递账单")
            .Distinct()
            .ToListAsync(a=> a.LogiAcct);


            //计算均摊
            //均摊配置
            var configs = await DB.FSql.Select<LogisticsFeeConfigItem>()
                .Where(a => a.Isdel == false && a.Enable == true)
                .ToListAsync();

            foreach (var item in configs)
            {
                item.AcctItems = await DB.FSql.Select<LogiFeeConfigAcctItem>()
                    .Where(a => a.DocId == item.id)
                    .ToListAsync();
                item.StockItems = await DB.FSql.Select<LogiFeeConfigStockItem>()
                    .Where(a => a.DocId == item.id)
                    .ToListAsync();
            }

            foreach (var conf in configs)
            {
                var temp = res.AsEnumerable();

                // 是否: 账单里没有 但是有出库的 , 需要单独核算 
                temp = temp.Where(a => a.NotInOutstock == conf.NoOutstock);

                //
                if (conf.AcctItems?.Any()== true)
                {
                    //查找相同快递账户的
                    temp = temp.Where(a => conf.AcctItems.Any(c=> c.LogiAcct == a.LogiAcct ));
                }
                if (conf.StockItems?.Any() == true)
                {
                    temp = temp.Where(a => conf.StockItems.Any(c=>  c.Stock == a.warehouse )) ;
                }
                if (conf.MinQty > 0)
                {
                    if (conf.Method == "按重量加价")
                    {
                        temp = temp.Where(a => a.weight >= conf.MinQty);
                    }
                    else if (conf.Method == "按金额加价")
                    {
                        temp = temp.Where(a => a.post_amount >= conf.MinQty);
                    }
                }

                if (conf.MaxQty > 0)
                {
                    if (conf.Method == "按重量加价")
                    {
                        temp = temp.Where(a => a.weight <= conf.MaxQty);
                    }
                    else if (conf.Method == "按金额加价")
                    {
                        temp = temp.Where(a => a.post_amount <= conf.MaxQty);
                    }
                }


                //按照条件(仓库或快递账户)筛选出的结果 
                
                var data = temp.ToList();

                int scal = 6;

                //计算
                if (data.Any() )
                {
                    if (conf.Method == "单数均摊")
                    {
                        var avg = Math.Round( conf.ShareAmount / data.Count(), scal, MidpointRounding.AwayFromZero) ;
                        //动态添加到列
                        res.AddRange(data.Select(a => new LogiFeeReport()
                        {
                            FeeGroupName = conf.ReportGroup,
                            LogiAcct = a.LogiAcct,
                            warehouse= a.warehouse,
                            IsForecast = false,
                            Fee = avg,
                            IsOnlyReport =true,
                        }));
                    }
                    else if (conf.Method == "重量均摊")
                    {
                        var wei = data.Sum(c => c.weight ?? 0m);
                        if (wei > 0)
                        {
                            var avg = Math.Round(conf.ShareAmount /wei, 8, MidpointRounding.AwayFromZero);
                            //动态添加到列
                            res.AddRange(data.Select(a => new LogiFeeReport()
                            {
                                FeeGroupName = conf.ReportGroup,
                                LogiAcct = a.LogiAcct,
                                warehouse = a.warehouse,
                                IsForecast = false,
                                Fee = Math.Round( avg* (a.weight ?? 0m), scal, MidpointRounding.AwayFromZero),
                                IsOnlyReport=true,
                            }));
                        }
         
                    }
                    else if (conf.Method == "按金额加价")
                    {
                        res.AddRange(data.Select(a => new LogiFeeReport()
                        {
                            FeeGroupName = conf.ReportGroup,
                            LogiAcct = a.LogiAcct,
                            warehouse = a.warehouse,
                            IsForecast = false,
                            Fee = (a.weight ?? 0m) * conf.AddPrice,
                            IsOnlyReport=true,
                        }));
                    }
                    else if (conf.Method == "按重量加价")
                    {
                        res.AddRange(data.Select(a => new LogiFeeReport()
                        {
                            FeeGroupName = conf.ReportGroup,
                            LogiAcct = a.LogiAcct,
                            warehouse = a.warehouse,
                            IsForecast = false,
                            Fee = (a.weight ?? 0m) * conf.AddPrice,
                            IsOnlyReport=true,
                        }));
                    }
                    else if (conf.Method == "按数量加价")
                    {
                        // 需要筛选单数
                        var isok = false;
                        if (conf.MaxQty > 0 && data.Count<= conf.MaxQty) 
                        {
                            isok = true;
                        }
                        if (conf.MinQty>0 && data.Count>= conf.MinQty)
                        {
                            isok = true;
                        }

                        if (isok )
                        {
                            res.AddRange(data.Select(a => new LogiFeeReport()
                            {
                                FeeGroupName = conf.ReportGroup,
                                LogiAcct = a.LogiAcct,
                                warehouse = a.warehouse,
                                IsForecast = false,
                                Fee = conf.AddPrice,
                                post_amount = a.post_amount,
                                IsOnlyReport=true,
                            }));
                        }
                     
                    }
                    else
                    {

                    }
                }
            }


            //合并报表
            // 快递老板	单数	账单情况	账单金额	总计	备注	原账单金额	预估或者在上个月账单里的	均摊费用金额	均摊车费1	均摊车费2	均摊车费3	匹配不上的均摊	最后总计

            var table = new DataTable();
            DataColumn cl_logiInfo, cl_qty, cl_BillingState, cl_LogiAmount, cl_total, cl_Remarks, cl_LogiAmount2, cl_ForecastAmount;

            table.Columns.Add(cl_logiInfo= new DataColumn(nameof(LogiFeeReport.LogiAcct), typeof(string)) { Caption= "快递老板" });
            table.Columns.Add(cl_qty = new DataColumn("qty", typeof(decimal)) { Caption = "单数", Namespace="#0.#########" });
            table.Columns.Add(cl_BillingState = new DataColumn(nameof(LogiFeeReport.BillingState), typeof(string)) { Caption = "账单情况" });
            table.Columns.Add(cl_LogiAmount = new DataColumn(nameof(LogiFeeReport.post_amount), typeof(decimal)) { Caption = "账单金额", Namespace = "#0.#########" });
            table.Columns.Add(cl_total =  new DataColumn("total", typeof(decimal)) { Caption= "总计", Namespace = "#0.#########" });
            table.Columns.Add(cl_Remarks =  new DataColumn(nameof(LogiFeeReport.Remarks), typeof(string)) { Caption= "备注" });
            table.Columns.Add(cl_LogiAmount2 =  new DataColumn(nameof(LogiFeeReport.post_amount) +"2", typeof(decimal)) { Caption= "原账单金额", Namespace = "#0.#########" });
            table.Columns.Add(cl_ForecastAmount =  new DataColumn(nameof(LogiFeeReport.ForecastAmount), typeof(decimal)) { Caption= "预估或者在上个月账单里的", Namespace = "#0.#########" });
            //table.Columns.Add(cl_Fee = new DataColumn(nameof(LogiFeeReport.Fee), typeof(decimal)) { Caption = "均摊费用" });

            var dynaCols = configs.Select(a => a.ReportGroup).Distinct().ToArray();
            foreach (var item in dynaCols)
            {
                table.Columns.Add(new DataColumn(item, typeof(decimal)){ Caption = item, Namespace = "#0.#########" });
            }
    
            var res3 = res.GroupBy(a => a.LogiAcct)
                .Select(a =>
                {
                    var dict = new Dictionary<string, decimal>();
                    foreach (var conf in dynaCols)
                    {
                        dict.Add(conf, a.Where(c => c.FeeGroupName == conf).DefaultIfEmpty()?.Sum(c => c?.Fee) ?? 0m);
                    }

                    return new
                    {
                        logiAcct= a.Key,
                        qty = a.Where(c=> c.IsOnlyReport== false).Count(),        // 排除费用
                        BillingState = billTotal.Contains(a.Key) ? "有" : "",     //有了导入的物流账单,提示有
                        ForecastAmount = a.Sum(c => c.ForecastAmount),
                        LogiAmount = a.Sum(c => c.post_amount),   //原账单
                        Fee = a.Sum(c => c.Fee),   //均摊费用
                        dict,
                    };
                })
                .ToList();

            foreach (var a in res3)
            {
                var dataRow = table.NewRow();
                dataRow[cl_logiInfo] = a.logiAcct;
                dataRow[cl_qty] = a.qty;
                dataRow[cl_BillingState] = a.BillingState;
                dataRow[cl_LogiAmount] = a.LogiAmount;
                dataRow[cl_total] = a.ForecastAmount + a.Fee + a.LogiAmount;
                dataRow[cl_Remarks] = string.Empty;
                dataRow[cl_LogiAmount2] =  a.LogiAmount;
                //dataRow[cl_Fee] = a.Fee;
                dataRow[cl_ForecastAmount] = a.ForecastAmount;

                foreach (var item in a.dict)
                {
                    dataRow[item.Key] = item.Value;
                }
                table.Rows.Add(dataRow);
            }


            return table;
        }


        public async Task<(DataTable, DataTable)> QueryFeeReport2(DateTime begin, DateTime end, bool getDetail)
        {
            begin = begin.Date;
            end = end.LastTimeOfDay();

            var res = (await QueryFeeReportDetails(begin, end, false)) as List<LogiFeeReport>;


            //费用账单, 
            // todo 怎么用 
            var feeBill = await DB.FSql.Select<LogisticsBillItem>()
                .Where(a => a.FMonth >= begin && a.FMonth <= end && a.BillFlag == "物流费用")
                .ToListAsync();

            var billTotal = await DB.FSql.Select<LogisticsBillItem>()
            .Where(a => a.FMonth >= begin && a.FMonth <= end && a.BillFlag == "快递账单")
            .Distinct()
            .ToListAsync(a => a.LogiAcct);


            //计算均摊
            //均摊配置
            var configs = await DB.FSql.Select<LogisticsFeeConfigItem>()
                .Where(a => a.Isdel == false && a.Enable == true)
                .ToListAsync();

            foreach (var item in configs)
            {
                item.AcctItems = await DB.FSql.Select<LogiFeeConfigAcctItem>()
                    .Where(a => a.DocId == item.id)
                    .ToListAsync();
                item.StockItems = await DB.FSql.Select<LogiFeeConfigStockItem>()
                    .Where(a => a.DocId == item.id)
                    .ToListAsync();
            }

            foreach (var conf in configs)
            {
                var temp = res.AsEnumerable();

                // 是否: 账单里没有 但是有出库的 , 需要单独核算 
                temp = temp.Where(a => a.NotInOutstock == conf.NoOutstock);

                //
                if (conf.AcctItems?.Any() == true)
                {
                    //查找相同快递账户的
                    temp = temp.Where(a => conf.AcctItems.Any(c => c.LogiAcct == a.LogiAcct));
                }
                if (conf.StockItems?.Any() == true)
                {
                    temp = temp.Where(a => conf.StockItems.Any(c => c.Stock == a.warehouse));
                }
                if (conf.MinQty > 0)
                {
                    if (conf.Method == "按重量加价")
                    {
                        temp = temp.Where(a => a.weight >= conf.MinQty);
                    }
                    else if (conf.Method == "按金额加价")
                    {
                        temp = temp.Where(a => a.post_amount >= conf.MinQty);
                    }
                }

                if (conf.MaxQty > 0)
                {
                    if (conf.Method == "按重量加价")
                    {
                        temp = temp.Where(a => a.weight <= conf.MaxQty);
                    }
                    else if (conf.Method == "按金额加价")
                    {
                        temp = temp.Where(a => a.post_amount <= conf.MaxQty);
                    }
                }


                //按照条件(仓库或快递账户)筛选出的结果 

                var data = temp.ToList();

                int scal = 6;

                //计算
                if (data.Any())
                {
                    if (conf.Method == "单数均摊")
                    {
                        var avg = Math.Round(conf.ShareAmount / data.Count(), scal, MidpointRounding.AwayFromZero);
                        foreach (var item2 in data )
                        {
                            if (item2.FenTan == null) item2.FenTan = new List<SubFee>();

                            item2.FenTan.Add(new SubFee() { ReportGroup= conf.ReportGroup, Fee= avg }) ;
                        }
                        ////动态添加到列
                        //res.AddRange(data.Select(a => new LogiFeeReport()
                        //{
                        //    FeeGroupName = conf.ReportGroup,
                        //    LogiAcct = a.LogiAcct,
                        //    warehouse = a.warehouse,
                        //    IsForecast = false,
                        //    Fee = avg,
                        //    IsOnlyReport = true,
                        //}));
                    }
                    else if (conf.Method == "重量均摊")
                    {
                        var wei = data.Sum(c => c.weight ?? 0m);
                        if (wei > 0)
                        {
                            var avg = Math.Round(conf.ShareAmount / wei, 8, MidpointRounding.AwayFromZero);

                            foreach (var item2 in data)
                            {
                                if (item2.weight> 0)
                                {
                                    if (item2.FenTan == null) item2.FenTan = new List<SubFee>();

                                    item2.FenTan.Add(new SubFee() { ReportGroup = conf.ReportGroup, Fee = avg * (item2.weight ?? 0m) });
                                }
                                
                            }


                            //动态添加到列
                            //res.AddRange(data.Select(a => new LogiFeeReport()
                            //{
                            //    FeeGroupName = conf.ReportGroup,
                            //    LogiAcct = a.LogiAcct,
                            //    warehouse = a.warehouse,
                            //    IsForecast = false,
                            //    Fee = Math.Round(avg * (a.weight ?? 0m), scal, MidpointRounding.AwayFromZero),
                            //    IsOnlyReport = true,
                            //}));
                        }

                    }
                    else if (conf.Method == "按金额加价")
                    {
                        foreach (var item2 in data)
                        {
                            if (item2.FenTan == null) item2.FenTan = new List<SubFee>();

                            item2.FenTan.Add(new SubFee() { ReportGroup = conf.ReportGroup, Fee = (item2.weight ?? 0m) * conf.AddPrice });
                        }


                        //res.AddRange(data.Select(a => new LogiFeeReport()
                        //{
                        //    FeeGroupName = conf.ReportGroup,
                        //    LogiAcct = a.LogiAcct,
                        //    warehouse = a.warehouse,
                        //    IsForecast = false,
                        //    Fee = (a.weight ?? 0m) * conf.AddPrice,
                        //    IsOnlyReport = true,
                        //}));
                    }
                    else if (conf.Method == "按重量加价")
                    {
                        foreach (var item2 in data)
                        {
                            if (item2.FenTan == null) item2.FenTan = new List<SubFee>();

                            item2.FenTan.Add(new SubFee() { ReportGroup = conf.ReportGroup, Fee = (item2.weight ?? 0m) * conf.AddPrice });
                        }

                        //res.AddRange(data.Select(a => new LogiFeeReport()
                        //{
                        //    FeeGroupName = conf.ReportGroup,
                        //    LogiAcct = a.LogiAcct,
                        //    warehouse = a.warehouse,
                        //    IsForecast = false,
                        //    Fee = (a.weight ?? 0m) * conf.AddPrice,
                        //    IsOnlyReport = true,
                        //}));
                    }
                    else if (conf.Method == "按数量加价")
                    {
                        // 需要筛选单数
                        var isok = false;
                        if (conf.MaxQty > 0 && data.Count <= conf.MaxQty)
                        {
                            isok = true;
                        }
                        if (conf.MinQty > 0 && data.Count >= conf.MinQty)
                        {
                            isok = true;
                        }

                        if (isok)
                        {
                            foreach (var item2 in data)
                            {
                                if (item2.FenTan == null) item2.FenTan = new List<SubFee>();

                                item2.FenTan.Add(new SubFee() { ReportGroup = conf.ReportGroup, Fee = conf.AddPrice });
                            }
                            //res.AddRange(data.Select(a => new LogiFeeReport()
                            //{
                            //    FeeGroupName = conf.ReportGroup,
                            //    LogiAcct = a.LogiAcct,
                            //    warehouse = a.warehouse,
                            //    IsForecast = false,
                            //    Fee = conf.AddPrice,
                            //    post_amount = 0,
                            //    IsOnlyReport = true,
                            //}));
                        }

                    } 
                }
            }


            //合并报表
            // 快递老板	单数	账单情况	账单金额	总计	备注	原账单金额	预估或者在上个月账单里的	均摊费用金额	均摊车费1	均摊车费2	均摊车费3	匹配不上的均摊	最后总计

            var table = new DataTable();
            DataColumn cl_logiInfo, cl_qty, cl_BillingState, cl_LogiAmount, cl_total, cl_Remarks, cl_LogiAmount2, cl_ForecastAmount;

            table.Columns.Add(cl_logiInfo = new DataColumn(nameof(LogiFeeReport.LogiAcct), typeof(string)) { Caption = "快递老板" });
            table.Columns.Add(cl_qty = new DataColumn("qty", typeof(decimal)) { Caption = "单数", Namespace = "#0.#########" });
            table.Columns.Add(cl_BillingState = new DataColumn(nameof(LogiFeeReport.BillingState), typeof(string)) { Caption = "账单情况" });
            table.Columns.Add(cl_LogiAmount = new DataColumn(nameof(LogiFeeReport.post_amount), typeof(decimal)) { Caption = "账单金额", Namespace = "#0.#########" });
            table.Columns.Add(cl_total = new DataColumn("total", typeof(decimal)) { Caption = "总计", Namespace = "#0.#########" });
            table.Columns.Add(cl_Remarks = new DataColumn(nameof(LogiFeeReport.Remarks), typeof(string)) { Caption = "备注" });
            table.Columns.Add(cl_LogiAmount2 = new DataColumn(nameof(LogiFeeReport.post_amount) + "2", typeof(decimal)) { Caption = "原账单金额", Namespace = "#0.#########" });
            table.Columns.Add(cl_ForecastAmount = new DataColumn(nameof(LogiFeeReport.ForecastAmount), typeof(decimal)) { Caption = "预估或者在上个月账单里的", Namespace = "#0.#########" });
            //table.Columns.Add(cl_Fee = new DataColumn(nameof(LogiFeeReport.Fee), typeof(decimal)) { Caption = "均摊费用" });

            //分摊金额的列 
            var dynaCols = configs.Select(a => a.ReportGroup).Distinct().ToArray();
            foreach (var item in dynaCols)
            {
                table.Columns.Add(new DataColumn(item, typeof(decimal)) { Caption = item, Namespace = "#0.#########" });
            }

            //var res3 = res.GroupBy(a => a.LogiAcct)
            //    .Select(a =>
            //    {
            //        var dict = new Dictionary<string, decimal>();
            //        foreach (var conf in dynaCols)
            //        {
            //            dict.Add(conf, a.Where(c => c.FeeGroupName == conf).DefaultIfEmpty()?.Sum(c => c?.Fee) ?? 0m);
            //        }

            //        return new
            //        {
            //            logiAcct = a.Key,
            //            qty = a.Where(c => c.IsOnlyReport == false).Count(),        // 排除费用
            //            BillingState = billTotal.Contains(a.Key) ? "有" : "",     //有了导入的物流账单,提示有
            //            ForecastAmount = a.Sum(c => c.ForecastAmount),
            //            LogiAmount = a.Sum(c => c.post_amount),   //原账单
            //            Fee = a.Sum(c => c.Fee),   //均摊费用
            //            dict,
            //        };
            //    })
            //    .ToList();

            //foreach (var a in res3)
            //{
            //    var dataRow = table.NewRow();
            //    dataRow[cl_logiInfo] = a.logiAcct;
            //    dataRow[cl_qty] = a.qty;
            //    dataRow[cl_BillingState] = a.BillingState;
            //    dataRow[cl_LogiAmount] = a.LogiAmount;
            //    dataRow[cl_total] = a.ForecastAmount + a.Fee + a.LogiAmount;
            //    dataRow[cl_Remarks] = string.Empty;
            //    dataRow[cl_LogiAmount2] = a.LogiAmount;
            //    //dataRow[cl_Fee] = a.Fee;
            //    dataRow[cl_ForecastAmount] = a.ForecastAmount;

            //    foreach (var item in a.dict)
            //    {
            //        dataRow[item.Key] = item.Value;
            //    }
            //    table.Rows.Add(dataRow);
            //}

            int rptScal = 3;

            var res4 = res.GroupBy(a => a.LogiAcct)
                .Select(a =>
                {
                    var fees = a.Where(c => c.FenTan != null).SelectMany(a => a.FenTan);

                    return new
                    {
                        logiAcct = a.Key,
                        qty = a.Where(c => c.IsOnlyReport == false).Count(),        // 排除费用
                        BillingState = billTotal.Contains(a.Key) ? "有" : "",     //有了导入的物流账单,提示有
                        ForecastAmount = Math.Round( a.Sum(c => c.ForecastAmount), rptScal, MidpointRounding.AwayFromZero),
                        LogiAmount = a.Sum(c => c.post_amount),   //原账单
                        Fee = Math.Round( fees?.Any() == true ? fees.Sum(c => c?.Fee ?? 0m) : 0m, rptScal, MidpointRounding.AwayFromZero),   //均摊费用
                        fentan = fees,
                    };
                });

            foreach (var a in res4)
            {
                var dataRow = table.NewRow();
                dataRow[cl_logiInfo] = a.logiAcct;
                dataRow[cl_qty] = a.qty;
                dataRow[cl_BillingState] = a.BillingState;
                dataRow[cl_LogiAmount] = a.LogiAmount;
                
                dataRow[cl_Remarks] = string.Empty;
                dataRow[cl_LogiAmount2] = a.LogiAmount;
                dataRow[cl_ForecastAmount] = a.ForecastAmount;

                if (a.fentan != null)
                {
                    foreach (var item in 
                        a.fentan.GroupBy(c=> c.ReportGroup)
                            .Select(c=> new {c.Key, fee= c.Sum(d=> d.Fee)}))
                    {
                        dataRow[item.Key] = Math.Round( item.fee, rptScal, MidpointRounding.AwayFromZero);
                    }
                }

                dataRow[cl_total] = a.ForecastAmount + a.Fee + a.LogiAmount;

                table.Rows.Add(dataRow);
            }


            var table2 = new DataTable();

            if (getDetail)
            {
                // 明细表格
                DataColumn cl_total2, cl_logistics_no, cl_num, cl_trade_no, cl_src_tids, cl_trade_type, cl_warehouse, cl_shop_name,
                    cl_spec_no, cl_rece_province, cl_logistics_name, cl_LogiAcct, cl_cs_remark, cl_consign_time, cl_post_amount, cl_weight, cl_ForecastAmount3, cl_IsForecastText, cl_NoLogiTraceText, cl_NotInOutstockText;

                table2.Columns.Add(cl_logistics_no = new DataColumn(nameof(LogiFeeReport.logistics_no), typeof(string)) { Caption = "物流单号" });
                table2.Columns.Add(cl_num = new DataColumn("num", typeof(decimal)) { Caption = "货品数量",});
                table2.Columns.Add(cl_trade_no = new DataColumn(nameof(LogiFeeReport.trade_no), typeof(string)) { Caption = "订单编号" });
                table2.Columns.Add(cl_src_tids = new DataColumn(nameof(LogiFeeReport.src_tids), typeof(string)) { Caption = "原始单号",  });
                table2.Columns.Add(cl_trade_type = new DataColumn("trade_type", typeof(string)) { Caption = "订单类型"});
                table2.Columns.Add(cl_warehouse = new DataColumn(nameof(LogiFeeReport.warehouse), typeof(string)) { Caption = "仓库" });
                table2.Columns.Add(cl_shop_name = new DataColumn(nameof(LogiFeeReport.shop_name), typeof(string)) { Caption = "店铺" });
                table2.Columns.Add(cl_spec_no = new DataColumn(nameof(LogiFeeReport.spec_no), typeof(string)) { Caption = "商家编码" });
                table2.Columns.Add(cl_rece_province = new DataColumn(nameof(LogiFeeReport.rece_province), typeof(string)) { Caption = "收货地区" });
                table2.Columns.Add(cl_logistics_name = new DataColumn(nameof(LogiFeeReport.logistics_name), typeof(string)) { Caption = "物流公司" });
                table2.Columns.Add(cl_LogiAcct = new DataColumn(nameof(LogiFeeReport.LogiAcct), typeof(string)) { Caption = "快递老板" });
                table2.Columns.Add(cl_cs_remark = new DataColumn(nameof(LogiFeeReport.cs_remark), typeof(string)) { Caption = "客服备注" });
                table2.Columns.Add(cl_consign_time = new DataColumn(nameof(LogiFeeReport.consign_time), typeof(DateTime)) { Caption = "发货时间", Namespace="yyyy-MM-dd HH:mm:ss" });
                table2.Columns.Add(cl_post_amount = new DataColumn(nameof(LogiFeeReport.post_amount), typeof(decimal)) { Caption = "结算运费", });
                table2.Columns.Add(cl_weight = new DataColumn(nameof(LogiFeeReport.weight), typeof(decimal)) { Caption = "结算重量", });
                table2.Columns.Add(cl_ForecastAmount3 = new DataColumn(nameof(LogiFeeReport.ForecastAmount), typeof(decimal)) { Caption = "预估运费", Namespace = "#0.########" });
                table2.Columns.Add(cl_IsForecastText = new DataColumn(nameof(LogiFeeReport.IsForecastText), typeof(string)) { Caption = "是否预估" });
                table2.Columns.Add(cl_NoLogiTraceText = new DataColumn(nameof(LogiFeeReport.NoLogiTraceText), typeof(string)) { Caption = "无快递记录" });
                table2.Columns.Add(cl_NotInOutstockText = new DataColumn(nameof(LogiFeeReport.NotInOutstockText), typeof(string)) { Caption = "无出库信息" });
                table2.Columns.Add(cl_total2 = new DataColumn(nameof(LogiFeeReport.Total), typeof(decimal)) { Caption = "合计" , Namespace="@"});

                //分摊金额的列 
                foreach (var item in dynaCols)
                {
                    table2.Columns.Add(new DataColumn(item, typeof(decimal)) { Caption = item, Namespace = "#0.#########" });
                }

                foreach (var a in res)
                {
                    var dataRow = table2.NewRow();

                    dataRow[cl_logistics_no] = a.logistics_no;
                    dataRow[cl_num] = a.num;
                    dataRow[cl_trade_no] = a.trade_no;
                    dataRow[cl_src_tids] = a.src_tids;
                    dataRow[cl_trade_type] = a.trade_type;
                    dataRow[cl_warehouse] = a.warehouse;
                    dataRow[cl_shop_name] = a.shop_name;
                    dataRow[cl_spec_no] = a.spec_no;
                    dataRow[cl_rece_province] = a.rece_province;
                    dataRow[cl_logistics_name] = a.logistics_name;
                    dataRow[cl_LogiAcct] = a.LogiAcct;
                    dataRow[cl_cs_remark] = a.cs_remark;
                    if (a.consign_time != null)
                        dataRow[cl_consign_time] = a.consign_time ;
                    else
                    {
                        dataRow[cl_consign_time] = DBNull.Value;
                    }
                    dataRow[cl_post_amount] = a.post_amount;
                    dataRow[cl_weight] = a.weight ?? 0m;
                    dataRow[cl_ForecastAmount3] = a.ForecastAmount ;
                    dataRow[cl_IsForecastText] = a.IsForecastText;
                    dataRow[cl_NoLogiTraceText] = a.NoLogiTraceText;
                    dataRow[cl_NotInOutstockText] = a.NotInOutstockText;

                    decimal total = 0m;
                    if (a.FenTan != null)
                    {
                        foreach (var item in a.FenTan)
                        {
                            dataRow[item.ReportGroup] = item.Fee;
                            total+= item.Fee;   
                        }
                    }

                    dataRow[cl_total2] = a.ForecastAmount + a.post_amount + total;

                    table2.Rows.Add(dataRow);
                }

            }

            return (table, table2);
        }



        /// <summary> 预估邮费 </summary>
        private decimal Yugu(LogiFeeReport item, IEnumerable<LogiFeeReport> outList)
        {
            //计算方法
            // 账单中相同快递公司的平均运费,  加上 0.3*平均重量 

            var scal = 4;

            var avg = outList
                .Where(a => a.LogiAcct == item.LogiAcct)  //快递;
                .Where(a => a.rece_province == item.rece_province)   //省份
                .Where(a => a.shop_name == item.shop_name)   //店铺
                .GroupBy(a => new { a.LogiAcct })
                .Select(a => new
                {
                    a.Key,
                    total = a.Sum(c => c.post_amount),
                    weight = a.Sum(c => c.weight),
                    count = a.Count(),
                })
                .FirstOrDefault();

            if (avg == null)
            {
                // 忽略省份 再次查找
                avg = outList
                       .Where(a => a.LogiAcct == item.LogiAcct)  //快递公司;
                       .Where(a => a.shop_name == item.shop_name)   //店铺
                       .GroupBy(a => new { a.LogiAcct })
                       .Select(a => new
                       {
                           a.Key,
                           total = a.Sum(c => c.post_amount),
                           weight = a.Sum(c => c.weight),
                           count = a.Count(),
                       })
                       .FirstOrDefault ();
            }

            if (avg != null)
            {

                return Math.Round(avg.total /avg.count + (avg.weight ?? 0m) / avg.count *0.3m , scal);
            }

            return 0m;
        }



        #region Ipage 接口 

        public string Title => "核算配置";

        public bool EnableEditOnList => false;

        public bool EnableCreateOnList => false;

        public bool RefreshOnOpen => false;


        public LogisticsFeeConfigItem CopyItem(LogisticsFeeConfigItem item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.id = 0;
            newItem.Isdel = false;

            return newItem;
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<LogisticsFeeConfigItem>()
                .Where(a => a.id == id && a.Isdel == false)
                .ExecuteAffrowsAsync();

            await DB.FSql.Insert(new CLogs()
            {
                DocName = nameof(LogisticsFeeConfigItem),
                Computer = UserBll.CurrentUser.ComputerInfo,
                Zdr = UserBll.CurrentUser.Name,
                DocId = id.ToString(),
                DocAction = "删除",
            })
                .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string columnName, object value, LogisticsFeeConfigItem data)
        {
            return await Task.FromResult(new Result<int>(true));
        }

        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
            {
                new DeclareColumn(nameof(LogisticsFeeConfigItem.id),"id"){ Visible= false},
                new DeclareColumn(nameof(LogisticsFeeConfigItem.ReportGroup),"报表分组"),
                new DeclareColumn(nameof(LogisticsFeeConfigItem.Method),"核算方式"),
                //new DeclareColumn(nameof(LogisticsFeeConfigItem.LogiAccountText),"快递账户"),
                //new DeclareColumn(nameof(LogisticsFeeConfigItem.StockText),"仓库"),
                new DeclareColumn(nameof(LogisticsFeeConfigItem.ShareAmount),"分摊金额"),
                new DeclareColumn(nameof(LogisticsFeeConfigItem.AddPrice),"单件加价"),
                new DeclareColumn(nameof(LogisticsFeeConfigItem.MinQty),"最小量"),
                new DeclareColumn(nameof(LogisticsFeeConfigItem.MaxQty),"最大量"),
                new DeclareColumn(nameof(LogisticsFeeConfigItem.FUser),"制单人"),
            };
        }

        public async Task<LogisticsFeeConfigItem> GetItem(int id)
        {
            return await DB.FSql.Select<LogisticsFeeConfigItem>()
                .Where(a => a.Isdel == false && a.id == id)
                .ToOneAsync();
        }


        #region 查询参数

        //private DateTime? _begin;
        //private DateTime? _end;
        private string _find;


        #endregion

        /// <summary> 查询ui </summary>
        public ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                //.Add<DateTime?>(ControlEnum.gtDatePicker, "起始日期", c => _begin = c)
                //.Add<DateTime?>(ControlEnum.gtDatePicker, "截止日期", c => _end = c)
                .Add<string>(ControlEnum.guanTextBox, "查找", c => _find = c)
                .AddQueryButton("查询");

        }

        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<LogisticsFeeConfigItem>> QueryPage(DocFilterParameter queryPara)
        {

            var list = await DB.FSql.Select<LogisticsFeeConfigItem>()
                .Where(a => a.Isdel == false)
                .WhereIf(!string.IsNullOrEmpty(_find), a => a.ReportGroup.Contains(_find) )
                .Page(queryPara.PageNo, queryPara.PageSize)
                //.OrderByDescending(a => a.OccurDate)
                .OrderByDescending(a => a.id)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<LogisticsFeeConfigItem>(true, null, list, c);
        }



        public async Task<Result> SaveItem(LogisticsFeeConfigItem item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }


            string err = string.Empty;
            if (string.IsNullOrEmpty(item.ReportGroup))
            {
                err += "报表分组不能为空!";
            }
            if (string.IsNullOrEmpty(item.Method))
            {
                err += "核算方式不能为空";
            }


            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }



            item.Isdel = false;
            item.FTime = await DB.FSql.GetTimeAsync();
            item.FUser = UserBll.CurrentUser.Name;

            if (item.id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.id = (int)id;
            }
            else
            {
                //删除旧的
                await DB.FSql.Delete<LogiFeeConfigAcctItem>()
                    .Where(a => a.DocId == item.id)
                    .ExecuteAffrowsAsync();
                await DB.FSql.Delete<LogiFeeConfigStockItem>()
                    .Where(a => a.DocId == item.id)
                    .ExecuteAffrowsAsync();

                await DB.FSql.Update<LogisticsFeeConfigItem>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            foreach (var it in item.AcctItems)
            {
                it.DocId = item.id;
            }

            foreach (var it in item.StockItems)
            {
                it.DocId = item.id;
            }

            await DB.FSql.Insert(item.AcctItems).ExecuteIdentityAsync();
            await DB.FSql.Insert(item.StockItems).ExecuteIdentityAsync();

            return new Result(true);

        }

        public LogisticsFeeConfigItem CreateItem()
        {
            return new LogisticsFeeConfigItem() { Isdel = false };
        }


        public async Task<List<LogiFeeConfigStockItem>> GetSotckItems(int id)
        {
            if (id<=0)
            {
                return new List<LogiFeeConfigStockItem>();
            }

            return await DB.FSql.Select<LogiFeeConfigStockItem>()
                .Where(a => a.DocId == id)
                .ToListAsync();
        }


        public async Task<List<LogiFeeConfigAcctItem>> GetAcctItems(int id)
        {
            if (id <= 0)
            {
                return new List<LogiFeeConfigAcctItem>();
            }

            return await DB.FSql.Select<LogiFeeConfigAcctItem>()
                .Where(a => a.DocId == id)
                .ToListAsync();
        }



        #endregion





        /// <summary> 无账单运费的单号 </summary>
        public async Task<IEnumerable<dynamic>> QueryQueryNoBill(DateTime begin, DateTime end)
        {
            begin = begin.Date;
            end = end.LastTimeOfDay();

            var res = await DB.FSql
              .Select<OutStockItem, LogiInfo, LogisticsBillItem >()
              .InnerJoin((a,b,c)=> a.logistics_name== b.logistics_name && b.isdel== false && b.IsAgent == false)
              .LeftJoin((a, b,c ) => a.logistics_no == c.LogisticCode && c.BillFlag == "快递账单" && c.FMonth >= begin && c.FMonth <= end)
              .Where((a, b, c) => a.consign_time >= begin && a.consign_time <= end)
              .Where((a,b, c)=> a.post_amount<=0 )
              .Where("c.id is null") 
              .ToListAsync((a, b, c ) => new 
              {
                  订单编号= a.trade_no,
                  发货时间= a.consign_time,
                  物流单号= a.logistics_no,
                  物流公司= a.logistics_name,
                  快递老板=b.LogiAcct,
                  邮费 = a.post_amount,
                  收货地址 = a.receiver_address,
                  收货地区 = a.receiver_position,
                  省份= a.rece_province,
                  城市=a.rece_city,
                  县市 =a.rece_county,
                  客服备注= a.cs_remark,
              });

            return res;
        }



    }





}



 
